package org.norocks.io;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * This wrapper is used to change HttpServletRequest parameters during
 * forwarding. It can be used instead of HttpServletRequest in method
 * RequestDispatcher.forward();
 * 
 * @author Dmitriy Bannikov
 * 
 */
public class HttpServletRequestWrapperLJ extends HttpServletRequestWrapper
{
	private Map<String, Object> params = new HashMap<String, Object>();

	/**
	 * Constructor.
	 * 
	 * @param request your HttpServletRequest
	 */
	public HttpServletRequestWrapperLJ(HttpServletRequest request)
	{
		super(request);
	}

	/**
	 * Changes HttpServletRequest parameter value, or adds new one.
	 * @param name parameter name
	 * @param value parameter value - single or array
	 */
	public void setParameter(String name, String... value)
	{
		params.put(name, value);
	}

	/**
	 * Uses new value of parameter, if it has been set.
	 * 
	 * @param name parameter name
	 * @return parameter value
	 */
	public String getParameter(String name)
	{
		String value = (String) params.get(name);
		if (value != null)
		{
			return value;
		}
		else
			return super.getParameter(name);
	}

	/**
	 * Uses new parameter values.
	 * @return parameters map
	 */
	public Map getParameterMap()
	{
		Map m = super.getParameterMap();
		for (Map.Entry<String, Object> e : params.entrySet())
		{
			if (m.keySet().contains(e.getKey()))
			{
				m.put(e.getKey(), e.getValue());
			}
		}
		return m;
	}

	/**
	 * Uses new parameter values.
	 * @param name parameter name
	 * @return array of values. If it's a single value, will return String[1]
	 */
	public String[] getParameterValues(String name)
	{
		Object value = params.get(name);
		if (value != null)
		{
			if (value instanceof String[])
			{
				return (String[]) value;
			}
			else
			{
				String[] param = new String[1];
				param[0] = value.toString();
				return param;
			}
		}
		else
			return super.getParameterValues(name);
	}
}
